package baobaotao.dao;

import baobaotao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Administrator on 2015/7/13.
 */
@Repository("userDao1")
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 据用户名和密码获取匹配的用户数
     * @param userName
     * @param password
     * @return
     */
    public int getMatchCount(String userName, String password) {
        String sqlStr = "select count(*) from t_user" + " where user_name = ? and password = ?";
        return jdbcTemplate.queryForInt(sqlStr, new Object[]{userName, password});
    }

    /**
     * 根据用户名获取User对象
     * @param userName
     * @return
     */
    public User findUserByUserName(final String userName) {
        String sqlStr = "select user_id,user_name,credits" + " from t_user where user_name = ?";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{userName},
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getLong("user_id"));
                        user.setUserName(userName);
                        user.setCredits(rs.getLong("credits"));
                    }
                });
        return user;
    }

    /**
     * 更新用户积分、最后登录IP以及最后登录时间
     * @param user
     */
    public void updateLoginInfo(User user) {
        String sqlStr = "update t_user set last_visit = ?,last_ip=?,credits=?" + " where user_id = ?";
        jdbcTemplate.update(sqlStr, new Object[]{user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()});
    }
}
